<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实现刮刮乐</title>
    <style>
        .img {
            width: 400px;
            height: 300px;
            position: absolute;
            left: 200px;
            z-index: -1;
        }
        canvas {
            margin-left: 200px;
        }
        body {
            margin: 0;
        }
    </style>
</head>

<body>
    <div class="img">
        <img src="./image/1.png" style="width:100%;height:100%;" />
    </div>
    <canvas id="canvas" width="400" height="300"></canvas>
    <script>
        let canvas = document.querySelector("#canvas");
        let context = canvas.getContext("2d");
        // 绘制涂层（灰色部分）
        context.beginPath();
        context.fillStyle = "grey";
        context.fillRect(0, 0, 400, 300); // 设置画布大小

        // 监听鼠标事件
        canvas.addEventListener("mousemove", (e) => {
            // 当鼠标左键按下&&移动鼠标时，清除鼠标附近涂层
            if (e.buttons === 1) { // 使用 e.buttons 检查左键是否按下
                const rect = canvas.getBoundingClientRect(); // 获取canvas的位置和尺寸
                const x = e.clientX - rect.left; // 相对于canvas的x坐标
                const y = e.clientY - rect.top; // 相对于canvas的y坐标
                context.globalCompositeOperation = "destination-out"; // 橡皮擦模式
                context.beginPath();
                // 以鼠标位置为圆心，半径为10px的圆
                context.arc(x, y, 10, 0, Math.PI * 2);
                context.fill();
            }
        });
    </script>
</body>
</html>